<?php
/**
 * Created by PhpStorm.
 * User: alinejun
 * Date: 2019/1/20
 * Time: 22:15
 */
namespace app\index\controller;

use app\common\model\Address;
use app\common\model\Category;
use app\common\model\User;
use think\Db;

class Order extends IndexBase{

    public function create()
    {
        $type = 1;
        $carid = input('param.')['carid'];
        $address_id = input('param.address_id');
        $uid = userLogin();
        if(isset($_POST['type'])){
            $type = $_POST['type'];
        }

        if($type){
            if(!$uid){
                $this->ajaxReturn(0,'请登录！',url('index/user/login'));
            }
            $user = (new User())->getUserInfo(['id'=>$uid]);
            $ids = $carid;
            $goods  =  (new \app\common\model\Car())->getByids($ids);
            $price = 0;
            $data = [];
            $sn = $this->getSn();
            //计算总价
            if(!is_array($goods)){
                $this->ajaxReturn(3,[],'数据错误!');
            }
            foreach ($goods as &$value){
                $value['goodsInfo'] = (new \app\common\model\Goods())->getGoodsById(['id'=>$value['goodsid']]);
                $price +=  $value['goodsInfo']['price'] * $value['num'];
            }
            //查找用户资金
            if($user['balance']<$price){
                $this->ajaxReturn(2,[],'余额不足!');
            }
            $res2 = [];
            foreach ($goods as $k => &$value){
                $data['order_no'] = $sn;
                $data['address_id'] = $address_id;
                $value['goodsInfo'] = (new \app\common\model\Goods())->getGoodsById(['id'=>$value['goodsid']]);
                $data['goods_id'] = $value['goodsInfo']['id'];
                $data['discount'] = $value['goodsInfo']['discount'];
                $data['userid'] =$uid;
                $data['num'] = $value['num'];
                $data['total_price'] = $value['goodsInfo']['price'] * $value['num'];
                $validate = new \app\common\validate\Order();
                if(!$validate->check($data)){
                    $this->ajaxReturn(2,[],$validate->getError());
                }
                $res2 = $this->createOrder($data,$price,$carid[$k]);
                $price +=  $value['goodsInfo']['price'] * $value['num'];
            }
            if(!$goods){
                $this->error('未选择商品',url('/index/index/index'));
            }
                $this->ajaxReturn($res2['code'],$res2['data'],$res2['msg']);
            
        }else{
            $sn = $this->getSn();
            $goods  = (new \app\common\model\Goods())->getGoodsById(['id'=>$carid[0]]);
            $data['order_no'] = $sn;
            $data['address_id'] = $address_id;
            $data['goods_id'] =$carid[0];
            $data['discount'] = $goods['discount'];
            $data['userid'] =$uid;
            $data['num'] = $_POST['num'];
            $data['total_price'] = $goods['price'] * $data['num'] ;
            $validate = new \app\common\validate\Order();
            if(!$validate->check($data)){
                $this->ajaxReturn(2,[],$validate->getError());
            }
            $res2 = $this->createOrder($data,$data['total_price'],$carid[0],0);
            $this->ajaxReturn($res2['code'],$res2['data'],$res2['msg']);
        }
    }

    /**
     * @param $data
     * @param $address_id 地址id
     * @param $userid 用户id
     * $total_price
     * @param $goodsid 商品id 以逗号隔开
     * @return array
     */
    public function createOrder($data,$balance,$carid,$type=1)
    {
        $data['status'] = 1;
        $data['type'] = 1;
        $data['status_time'] = date('Y-m-d H:i:s');
        $data['create_time'] = date('Y-m-d H:i:s');
        $order = new \app\common\model\Order();
        if(is_array($data)){
            $res = $order->add($data);
        }
        if($res){
            $res1 =(new User())->updateBalance($data['userid'],$balance);
            if(!$res1){
                return ['code'=>0,'msg'=>'余额扣除失败~','data'=>[]];
            }
        }
        if($res&&$res1&&$type){
           $res2 = (new \app\common\model\Car())->where('id','in',$carid)->setField('status',-1);
        }
        if($type){
            if($res1&&$res2&&$res){
                return ['code'=>1,'msg'=>'支付成功~','data'=>['url'=>url('/index/order/index')]];
            }
        }else{
            if($res1&&$res){
                return ['code'=>1,'msg'=>'支付成功~','data'=>['url'=>url('/index/order/index')]];
            }
        }
    }

    public function getSn()
    {
        $sn = date('YmdHis').rand(rand(10000,50000),rand(50001,99999));
        return  $sn;
    }

    public function buyGoods()
    {
        $uid =  userLogin();
        if(!$uid){
            $this->jump(RESULT_REDIRECT, '未登录', url('index/user/login'));
        }
        $goods =  new \app\common\model\Goods();
        $id = input('goodsid');
        $goodsDetail = $goods->search(['id'=>$id])->toArray()['data'];
        $address_list = (new Address())->search(['userid'=>$uid]);
        if(empty($address_list->toArray()['data'])){
            $this->jump(RESULT_REDIRECT, '请填写地址。', url('index/user/address'));
        }
        $category_list = (new Category())->search();
        $this->assign('category_list',$category_list->toArray()['data']);
        $this->assign('address_list',$address_list->toArray()['data']);
        $this->assign('goodsDetail',$goodsDetail[0]);
        if(isset($_GET['num'])){
            $this->assign('total_price',$_GET['num']*$goodsDetail[0]['price']);
        }else{
            $this->assign('total_price',$goodsDetail[0]['price']);
        }
        return $this->fetch('create');
    }

    public function index()
    {
        $uid =  userLogin();
        if(isset($_GET['type']) && $_GET['type']!=0){
            $where['type'] = input('param.type');
        }
        $search_key = isset($_REQUEST['search_key'])?  input('param.search_key') : '';
        if($search_key){
            $where['order_no'] = ['like',"%$search_key%"];
        }
        if(!$uid){
            $this->jump(RESULT_REDIRECT, '未登录', url('index/user/login'));
        }
        $where['userid'] = $uid;
        $order = new \app\common\model\Order();
        $data = $order->search($where,'*','id desc',10)->toArray();
        foreach ($data['data'] as &$value){
            $value['goodsInfo'] = (new \app\common\model\Goods())->getGoodsById(['id'=>$value['goods_id']]);
            $value['type'] = config('order_status')[$value['type']];
        }

        //dump($data['data']);exit;
        $this->assign('orderList',$data['data']);
        return $this->fetch('index');
    }

    public function detail()
    {
        $orderid = input('param.orderid');
        if(!$orderid){
            $this->error('参数错误~');
        }
        $orderInof = (new \app\common\model\Order())->getOrderById(['id'=>$orderid]);
        $orderInof['goodsInfo'] =   (new \app\common\model\Goods())->getGoodsById(['id'=>$orderInof['goods_id']]);
        //dump($orderInof);exit;
        $address_list = (new Address())->search(['id'=>$orderInof['address_id']]);
        $this->assign('address_list',$address_list->toArray()['data'][0]);
        $this->assign('orderInfo',$orderInof);
        return $this->fetch('detail');
    }
}